package com.ruoyi.xyq.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitMQConfig {

    // 声明延迟交换机（移除重复声明）
    @Bean
    public DirectExchange delayExchange() {
        return new DirectExchange("withdrawal.delay.exchange");
    }

    // 延迟队列（通过死信机制实现）
    @Bean
    public Queue delayQueue() {
        return QueueBuilder.durable("withdrawal.delay.queue")
                .deadLetterExchange("withdrawal.dead.letter.exchange") // 设置死信交换机
                .deadLetterRoutingKey("withdrawal.dead.letter.routing.key") // 设置死信路由键
                .ttl(1000*60) // 设置消息过期时间（60秒）
                .build();
    }

    // 死信队列（消息过期后实际消费的队列）
    @Bean
    public Queue deadLetterQueue() {
        return new Queue("withdrawal.dead.letter.queue", true);
    }

    // 死信交换机（消息过期后转发到这里）
    @Bean
    public DirectExchange deadLetterExchange() {
        return new DirectExchange("withdrawal.dead.letter.exchange");
    }

    // 绑定延迟队列到延迟交换机
    @Bean
    public Binding delayQueueBinding() {
        return BindingBuilder.bind(delayQueue()).to(delayExchange()).with("withdrawal.delay.routing.key");
    }

    // 绑定死信队列到死信交换机
    @Bean
    public Binding deadLetterBinding() {
        return BindingBuilder.bind(deadLetterQueue()).to(deadLetterExchange()).with("withdrawal.dead.letter.routing.key");
    }


    // 添加 JSON 消息转换器
    @Bean
    public MessageConverter jsonMessageConverter() {
        ObjectMapper mapper = new ObjectMapper();
        // 配置 ObjectMapper（可选）
        // mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        // mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        return new Jackson2JsonMessageConverter(mapper);
    }

    // 配置 RabbitTemplate 使用 JSON 转换器
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory,
                                         MessageConverter messageConverter) {
        RabbitTemplate template = new RabbitTemplate(connectionFactory);
        template.setMessageConverter(messageConverter);
        return template;
    }
}